package com.example.demojpa.controller;

import com.example.demojpa.config.AjaxResult;
import com.example.demojpa.config.MyLog;
import com.example.demojpa.dao.HobbyDao;
import com.example.demojpa.dao.StudenDao;
import com.example.demojpa.dao.StudentHobbyDao;
import com.example.demojpa.domain.Hobby;
import com.example.demojpa.domain.Student;
import com.example.demojpa.domain.StudentHobby;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("student")
@CrossOrigin
public class StudentController {

    @Autowired
    private StudenDao studenDao;

    @Autowired
    private HobbyDao hobbyDao;

    @Autowired
    private StudentHobbyDao studentHobbyDao;



    @MyLog(title = "查询",method = "getList")
    /*列表*/
    @RequestMapping("getList")
    public AjaxResult getList(@RequestParam(defaultValue = "1")Integer pageNum, @RequestParam(defaultValue = "3")Integer pageSize, Student student){

        //System.err.println(student);
        final PageRequest request = PageRequest.of(pageNum - 1, pageSize);

        Specification<Student> specification = new Specification<Student>() {
            @SneakyThrows
            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cd) {
                //保存查询条件
                List<Predicate> list = new ArrayList<>();
                Path name1 = root.get("name");

                Path join_date = root.get("joinDate");

                if (student.getName()!=null&&!student.equals("")){
                    final Predicate name = cd.like(name1, "%".concat(student.getName()).concat("%"));
                    list.add(name);
                }
                //等于
                /*if(!StringUtils.isEmpty(student.getName())){
                    final Predicate name = cd.equal(root.get("name"), student.getName());
                    list.add(name);
                }*/
                //大于等于
                if(student.getCreaDate()!=null&&!student.getCreaDate().equals("")){
                    final String z = student.getCreaDate().replace("Z", " UTC");

                    Predicate predicate = cd.greaterThanOrEqualTo(join_date,new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z").parse(z));
                    list.add(predicate);
                }
                //小于等于
                if(student.getEndDate()!=null){
                    final String z = student.getEndDate().replace("Z", " UTC");
                    Predicate predicate = cd.lessThanOrEqualTo(join_date, new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z").parse(z));
                    list.add(predicate);
                }
                return cd.and(list.toArray(new Predicate[list.size()]));
            }
        };
        final Page<Student> page = studenDao.findAll(specification, request);
        page.getContent().forEach(stu->{
            if (stu.getHobbyList()!=null&&stu.getHobbyList().size()>0){
                stu.getHobbyList().forEach(hobby -> {
                    if (stu.getHobbys()==null||stu.getHobbys().equals("")){
                        stu.setHobbys(hobby.getName()+"/");
                    }else{
                        stu.setHobbys(stu.getHobbys()+hobby.getName()+"/");
                    }
                });
            }
        });
        /*final PageRequest of = PageRequest.of(pageNum - 1, pageSize);

        final Page<Student> page = studenDao.findAll(of);
        for (Student stu : page.getContent()) {
            if (stu.getHobbyList()!=null&&stu.getHobbyList().size()>0){
                for (Hobby hobby : stu.getHobbyList()) {
                    if (stu.getHobbys()==null||stu.getHobbys().equals("")){
                        stu.setHobbys(hobby.getName()+"/");
                    }else{
                        stu.setHobbys(stu.getHobbys()+hobby.getName()+"/");
                    }
                }
            }
        }*/
        return AjaxResult.ok(page);
    }


    /*添加*/
    @PostMapping("addStudent")
    public AjaxResult addStudent(@RequestBody Student student){

        /*判断ID是否有值*/
        if (student.getId()!=null){
            /*ID不为NULL时，删除对应的中间表数据*/
            final List<StudentHobby> list = studentHobbyDao.findAllByStuId(student.getId());
            /*批删中间表*/
            studentHobbyDao.deleteAll(list);
        }

        /*因为前台写的方法不支持回显*/
        if (student.getHobbyList()!=null&&student.getHobbyList().size()>0){
            for (Hobby hobby : student.getHobbyList()) {
                Hobby allById = hobbyDao.findAllById(hobby.getId());
                System.err.println(allById);
                hobby.setName(allById.getName());
            }
        }

        /*先添加学生表*/
        final Student save = studenDao.save(student);
        System.err.println(student);
        return AjaxResult.ok();
    }

    /*删除*/
    @PostMapping("del")
    public AjaxResult del(@RequestBody Student student){
        studenDao.delete(student);
        return AjaxResult.ok();
    }
}
